#!/usr/bin/env bash
set -Eeuo pipefail

# --- Step 1: MIL version check (requires >= 3.4.0) ---
if ! command -v mx-ver >/dev/null 2>&1; then
  echo "ERROR: Could not find mx-ver command. Please run this script in a MIL environment."
  exit 1
fi

MIL_VER="$(mx-ver -M 2>/dev/null | tr -d '[:space:]')"
if [ -z "${MIL_VER:-}" ]; then
  echo "ERROR: Failed to detect MIL version."
  exit 1
fi

# Compare using Debian's dpkg version tool
if ! dpkg --compare-versions "$MIL_VER" ge "3.4.0"; then
  echo "WARNING: Current MIL version is ${MIL_VER} (below 3.4.0). This installation requires MIL >= 3.4.0. Exiting."
  exit 1
fi

# --- Extra: check user.yaml & cert.pem in script directory when TLS verification is enabled ---

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
USER_YAML="${SCRIPT_DIR}/user.yaml"
LOCAL_CERT="${SCRIPT_DIR}/cert.pem"

if [ -f "$USER_YAML" ]; then
  # Extract skipTLSVerify value (e.g., true / false)
  SKIP_TLS="$(awk -F: '/skipTLSVerify/{gsub(/[[:space:]]/,"",$2); print $2; exit}' "$USER_YAML" || true)"

  if [ "$SKIP_TLS" = "false" ]; then
    if [ ! -f "$LOCAL_CERT" ]; then
      echo "ERROR: security.skipTLSVerify is false in user.yaml, but cert.pem is missing in ${SCRIPT_DIR}."
      echo "Please place cert.pem in the same directory as this run script and user.yaml."
      echo "The certificate(cert.pem) is located under /var/lib/dlm/data/certs/root/ on the DLM server."
      exit 1
    fi
  fi
fi

set -Eeuo pipefail

# ======================
# Pretty logging helpers
# ======================
if [ -t 1 ]; then
  GREEN="\e[32m"; YELLOW="\e[33m"; RED="\e[31m"; CYAN="\e[36m"; BOLD="\e[1m"; DIM="\e[2m"; RESET="\e[0m"
else
  GREEN=""; YELLOW=""; RED=""; CYAN=""; BOLD=""; DIM=""; RESET=""
fi

log_info()  { echo -e "  ${GREEN}[INFO]${RESET} $*"; }
log_warn()  { echo -e "  ${YELLOW}[WARN]${RESET} $*"; }
log_error() { echo -e "  ${RED}[ERROR]${RESET} $*"; }
log_step()  { echo -e "${CYAN}${BOLD}Step ${CURRENT_STEP}/${TOTAL_STEPS}:${RESET} $*"; }

sep()       { echo -e "${DIM}------------------------------------------------------------${RESET}"; }

on_error() {
  log_error "Installation failed on Step ${CURRENT_STEP}. See messages above."
  echo
  exit 1
}
trap on_error ERR

# ======================
# Config
# ======================
AGENT_DIR="/etc/moxa/moxa-dlm-agent"
AGENT_SERVICE="moxa-dlm-agent"
USER_FILE="${AGENT_DIR}/user.yaml"
CERT_PEM="${AGENT_DIR}/cert.pem"
CREDENTIALS_ENC="${AGENT_DIR}/private/credentials.enc"

TOTAL_STEPS=6
CURRENT_STEP=0

# ======================
# Step 0: Header
# ======================
echo
sep
echo -e "${BOLD}Moxa DLM Agent Setup${RESET}"
sep
echo

# ======================
# Step 1: Ensure dirs & clear old token
# ======================
CURRENT_STEP=$((CURRENT_STEP+1))
log_step "Prepare agent directory & remove old tokens"
mkdir -p "$AGENT_DIR"
chmod 700 "$AGENT_DIR"
chown root:root "$AGENT_DIR"
log_info "Ensured ${AGENT_DIR} exists with 700 perms (root:root)."

if compgen -G "/etc/remoteagent/certs/*" > /dev/null 2>&1; then
  rm -rf /etc/remoteagent/certs/*
  log_info "Cleared /etc/remoteagent/certs/*"
else
  log_info "No legacy tokens in /etc/remoteagent/certs (nothing to clear)."
fi
echo

# ======================
# Step 2: Install or keep user.yaml
# ======================
CURRENT_STEP=$((CURRENT_STEP+1))
log_step "Install or keep user.yaml"
if [ -f ./user.yaml ]; then
  log_info "Installing user.yaml -> ${USER_FILE}"
  cp ./user.yaml "$USER_FILE"
  chmod 600 "$USER_FILE"
  chown root:root "$USER_FILE"
elif [ ! -f "$USER_FILE" ]; then
  log_error "user.yaml not provided and ${USER_FILE} does not exist."
  exit 1
else
  log_info "${USER_FILE} already exists; keeping current version."
fi
echo

# ======================
# Step 3: Install cert.pem if provided
# ======================
CURRENT_STEP=$((CURRENT_STEP+1))
log_step "Install cert.pem if provided"
if [ -f ./cert.pem ]; then
  log_info "Installing cert.pem -> ${CERT_PEM}"
  cp ./cert.pem "$CERT_PEM"
  chmod 600 "$CERT_PEM"
  chown root:root "$CERT_PEM"
elif [ ! -f "$CERT_PEM" ]; then
  log_warn "cert.pem not found (no new file and none installed). Skipping."
else
  log_info "${CERT_PEM} already exists; keeping current version."
fi
echo

# ======================
# Step 4: Install DLM package if available
# ======================
CURRENT_STEP=$((CURRENT_STEP+1))
log_step "Install DLM package if available"
if ls ./moxa-dlm-agent*.deb >/dev/null 2>&1; then
  log_info "Installing local package ./moxa-dlm-agent*.deb via apt-get"
  DEBIAN_FRONTEND=noninteractive apt-get install -y ./moxa-dlm-agent*.deb > /dev/null
  log_info "DLM package installation complete."
else
  log_info "No local moxa-dlm-agent*.deb found; skipping package install."
fi
echo

# ======================
# Step 5: Import or keep credentials
# ======================
CURRENT_STEP=$((CURRENT_STEP+1))
log_step "Import or keep credentials.yaml"
if [ -f ./credentials.yaml ]; then
  if ! command -v mx-dlm-agent >/dev/null 2>&1; then
    log_error "mx-dlm-agent not found in PATH; cannot import credentials."
    exit 1
  fi
  log_info "Importing credentials.yaml (tool will encrypt & store securely)"
  mx-dlm-agent import -f ./credentials.yaml
  # Best-effort cleanup if file still exists after import
  if [ -f ./credentials.yaml ]; then
    shred -u ./credentials.yaml || rm -f ./credentials.yaml || true
    log_info "Removed plaintext ./credentials.yaml after import."
  fi
elif [ ! -f "$CREDENTIALS_ENC" ]; then
  log_error "credentials.yaml not provided and ${CREDENTIALS_ENC} not found."
  exit 1
else
  log_info "${CREDENTIALS_ENC} already exists; keeping current version."
fi
echo

# ======================
# Step 6: Enable & restart service
# ======================
CURRENT_STEP=$((CURRENT_STEP+1))
log_step "Reload systemd, enable and restart agent service"
systemctl daemon-reload || true
systemctl enable "$AGENT_SERVICE" || true
systemctl restart "$AGENT_SERVICE" || true
log_info "Service ${AGENT_SERVICE} restarted."
echo

# ======================

# Step 7: Optional update for Moxa Connection Manager (MCM)
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"
MCM_DIR="${SCRIPT_DIR}/MCM"

if [ -d "${MCM_DIR}" ]; then
  shopt -s nullglob
  debs=( "${MCM_DIR}"/*.deb )
  if [ "${#debs[@]}" -gt 0 ]; then
    echo "Detected Moxa Connection Manager (MCM) update packages: ${#debs[@]} .deb file(s). Installing..."
    if command -v apt-get >/dev/null 2>&1; then
      set +e
      apt-get -y install "${debs[@]}"
      rc=$?
      set -e
      if [ $rc -ne 0 ]; then
        echo "apt installation failed, falling back to dpkg + dependency fix..."
        dpkg -i "${debs[@]}" || true
        apt-get -y -o APT::Install-Recommends="false" install -f
      fi
    else
      dpkg -i "${debs[@]}"
    fi
    echo "Moxa Connection Manager (MCM) update complete."
  else
    echo "MCM directory exists but contains no .deb files, skipping MCM installation."
  fi
else
  echo "No MCM update directory detected, skipping MCM installation."
fi

# Summary
# ======================
sep
echo -e "${GREEN}${BOLD}Installation complete.${RESET}"
echo "Next steps:"
echo "  • Run 'mx-dlm-agent status' to verify the enrollment status."
echo "  • If 'mx-dlm-agent status' shows 'The daemon is not running', run 'systemctl status ${AGENT_SERVICE}' to check service health and identify common issues such as incorrect credentials, wrong password, or configuration errors."
echo "  • If the service status does not provide enough information to determine the root cause, run collect_dlm_logs.sh to collect all necessary logs and report the case to Moxa customer service."
sep
echo
